package it.stessaro.lostcities.ai;

import it.stessaro.lostcities.collection.Card;
import it.stessaro.lostcities.collection.ColorPileSortByValue;
import it.stessaro.lostcities.collection.DiscardPiles;
import it.stessaro.lostcities.collection.ExpeditionPiles;
import it.stessaro.lostcities.collection.pile.ColorPile;
import it.stessaro.lostcities.collection.pile.Hand;
import it.stessaro.lostcities.core.Costants;
import it.stessaro.lostcities.core.Log;

import java.util.ArrayList;
import java.util.Collections;

public class MoveEngine extends ArrayList<ColorPile>{

	private static final long serialVersionUID = 1L;
	private ExpeditionPiles expeditions;
	
	public MoveEngine(ExpeditionPiles pcExpeditions) {
		this.init();
		this.expeditions = pcExpeditions;
	}
	public void init(){
		this.clear();
		this.add(Costants.RED, new ColorPile(Costants.RED));
		this.add(Costants.WHITE, new ColorPile(Costants.WHITE));
		this.add(Costants.GREEN, new ColorPile(Costants.GREEN));
		this.add(Costants.BLUE, new ColorPile(Costants.BLUE));
		this.add(Costants.YELLOW, new ColorPile(Costants.YELLOW));
	}
	
	public Card updateHand(Hand pcHand, ExpeditionPiles pcExpeditions, DiscardPiles discardPile, ExpeditionPiles playerExpeditions){
		Card choose = this.addCards(pcHand);
		Log.print(choose.toString());
		this.printValues();
		this.init();
		return choose;
		
	}
	
	public Card addCards(Hand hand){
		
		//TODO 1 priority most present color
		//TODO 2 priority most valuable color in hand
		//TODO 3 priority most valuable color in expedition
		//TODO 4 non priority for strong value exp player1
		//TODO 5 if no condition discard card bad value 
		this.init();
		for (Card card : hand) {
			int listPosition = card.getCardColor();//position
			this.get(listPosition).addCard(card);
		}
		//
		for(ColorPile exp: this){
			if (exp.size() == 0) {
				//TODO add weight
				exp.addWeight(-100);
			}
		}
		for(ColorPile exp: expeditions){
			int col = exp.getColor();
			this.get(col).addWeight(exp.value());
		}
		//
		this.sort();
		
		int index = 0;
		int index2 = 0;
		
		while(this.sizeOf(index) == 0 ){

			index++;
		}
		while(!this.isPlayable(index, index2)){
			index2++;
		}

		Log.print("best choice " + this.get(index).getColorString());
		
		Card e = this.get(index).elementAt(index2);
		return e;
	}
	

	private int sizeOf(int index ){
		return this.get(index).size();
	}
	private boolean isPlayable(int index, int index2){
		return expeditions.isCardPlayable(this.get(index).elementAt(index2));
	}
	public void sort(){
		Collections.sort(this, new ColorPileSortByValue());
	}
	public void printValues(){
		this.sort();
		for (ColorPile element : this) {
			System.out.println(element.getColorString() + " " +  element.value() + " " + element.expr_weight());
		}
	}
}
